package org.mclll.xwangplugin.questTracking.persistence;

import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.mclll.xwangplugin.log.GlobalLog;
import org.mclll.xwangplugin.log.LogUtil;
import org.mclll.xwangplugin.log.LoggerFactory;

import java.io.*;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static org.mclll.xwangplugin.questTracking.listener.QuestListener.*;

/**
 * @author: geduo
 * @date: 2023/10/14 18:35
 */
@Data
@AllArgsConstructor
public class Persistence implements Serializable {
    private static final LogUtil LOG = LoggerFactory.get(GlobalLog.class);

    private Map<UUID, Map<String, List<SerializeScore>>> A = Maps.newHashMap();

    private Map<UUID, Map<String, Integer>> B = Maps.newHashMap();

    private Map<UUID, String> C = Maps.newHashMap();

    public Persistence() {
    }


    @Data
    public static class SerializeScoreBoard implements Serializable {
        private List<SerializeScore> scores;
        private UUID playerUuid;
    }

    @Data
    @AllArgsConstructor
    public static class SerializeScore implements Serializable {
        private String name;
        private Integer value;

        public SerializeScore() {
        }
    }

    public static void saveScoreBoard(File file) {
        try (ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(new File(file, "scoreboard.bin").toPath()))) {
            // response设置下载文件，文件名称
            oos.writeObject(new Persistence(QUEST_SCOREBOARD_MAP, PLAYER_QUEST_STAGE_MAP, PLAYER_CURRENT_QUESTS));
            LOG.info("scoreboard已成功序列化并保存到文件 scoreboard.bin");
        } catch (IOException e) {
            LOG.error("序列化失败{0}", e.getCause());
        }
    }

    public static void loadScoreBoard(File file) {
        File file1 = new File(file, "scoreboard.bin");
        if (!file1.exists()) {
            return;
        }
        try (ObjectInputStream ois = new ObjectInputStream(Files.newInputStream(file1.toPath()))) {
            Persistence saveData = (Persistence) ois.readObject();
            QUEST_SCOREBOARD_MAP = saveData.getA();
            PLAYER_QUEST_STAGE_MAP = saveData.getB();
            PLAYER_CURRENT_QUESTS = saveData.getC();
            LOG.info("scoreboard已成功反序列化并加载");
        } catch (IOException | ClassNotFoundException e) {
            LOG.error("反序列化失败", e.getCause());
        }
    }

}
